from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator

from django.shortcuts import redirect
from django.urls import reverse
from django.db.models import Q
from common.models import Article
from PIL import Image
from datetime import datetime
import time,json,os


def article_index(request,pIndex=1):
    '''浏览信息'''
    #获取商品信息查询对象
    mod = Article.objects
    mywhere=[] #定义一个用于存放搜索条件列表

    # 获取、判断并封装关keyword键搜索
    kw = request.GET.get("keyword",None)
    if kw:
        # 查询商品名中只要含有关键字的都可以
        list1 = mod.filter(Q(name__contains=kw)&Q(recommend=1))
        mywhere.append("keyword="+kw)
    else:
        list1 = mod.filter(Q(recommend=1))

    # 获取、判断并封装商品状态typeid搜索条件
    typeid = request.GET.get('typeid','')
    if typeid != '':
        list1 = list1.filter(typeid=typeid)
        mywhere.append("typeid="+typeid)

    #执行分页处理
    pIndex = int(pIndex)
    page = Paginator(list1,12) #以12条每页创建分页对象
    maxpages = page.num_pages #最大页数
    #判断页数是否越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex) #当前页数据
    plist = page.page_range   #页码数列表
    px = pIndex
    plist2 = set()
    plist2.add(px)
    for x in range(1,6):
        if px-x >= 1 and len(plist2) <= 11:
            plist2.add(px-x)
        if px+x <= maxpages and len(plist2) <= 11:
            plist2.add(px+x)

    plist2 = list(plist2)
    plist2.sort()

    context = {"recomendlist":list2,'plist':plist2,'pIndex':pIndex,'maxpages':maxpages}

    return render(request,"myadmin/recommend/article_index.html",context)

def article_add(request):
    '''加载添加页面'''
    return render(request,"myadmin/recommend/article_add.html")

def article_insert(request):
    
    try:
        obid = request.POST['id']
        ob = Article.objects.get(id=obid)
        ob.recommend = 1
        ob.save()
        context = {"info":"修改成功！"}
    except Exception as err:
        print(err)
        context = {"info":"修改失败！"}
    return render(request,"myadmin/recommend/info.html",context)

def article_del(request,uid):
    try:
        ob = Article.objects.get(id=uid)
        ob.recommend = 0
        ob.save()
        context = {"info":"删除推荐课程成功！"}
    except Exception as err:
        print(err)
        context = {"info":"删除推荐课程失败！"}
    return render(request,"myadmin/recommend/info.html",context)
    